import datetime
import json
import urllib
from numpy import size
from fetch_info_to_file.ASIN import get_ASIN
import matplotlib.pyplot as plt
from fetch_info_to_file.Review_Stuff import Review_Stuff

class draw_reviewDistibution():
    top_count = []
    list = [0,0,0]
    
    def getCategory(self):
        #return 'Clothing $ Accessories>Women>Jeans'
        return 'Pet Supplies>Dogs>Food'
        #return 'Cell Phones $ Accessories>Cell Phones>Contract Cell Phones'
    def getLocalRecentReviewCount(self):
        lines = Review_Stuff().readFromLocal('baby_clothes_review')
        today = self.getLocalLastDay()
        for i in range(0,len(lines)):
            count = 0
            reviews = lines[i]['single_review']
            asin = lines[i]['ASIN']
            reviews_count = size(reviews)
            start_day = today-datetime.timedelta(weeks=8)
            for j in range(0,reviews_count):
                publish_time = datetime.datetime.strptime(str(reviews[j]['time']).split(' ')[0],"%Y-%m-%d")
                if(publish_time>=start_day):
                    count = count+1
            if count<20:
                self.list[0] = self.list[0]+1
            elif count<100:
                self.list[1] = self.list[1]+1
            else:
                self.list[2] = self.list[2]+1
            #save top 10 product
            if len(self.top_count)>=10:
                if self.top_count[9][1]<count:
                    self.top_count[9] = (asin,count)
                    self.top_count.sort(key=lambda x:x[1],reverse=True)
            else:
                temp = (asin,count)
                self.top_count.append(temp)
                self.top_count.sort(key=lambda x:x[1],reverse=True)
            
    #online
    def getRecentRievewCount(self,asin):
        count = 0
        product = self.get_product_data(asin)
        reviews = product['review']
        reviews_count = size(reviews)
        today = datetime.datetime(2014,3,8)
        start_day = today-datetime.timedelta(weeks=8)
        for i in range(0,reviews_count):
            publish_time = datetime.datetime.strptime(str(reviews[i]['publishTime']).split(' ')[0],"%Y-%m-%d")
            if(publish_time>=start_day):
                count = count+1
        if count<20:
            self.list[0] = self.list[0]+1
        elif count<100:
            self.list[1] = self.list[1]+1
        else:
            self.list[2] = self.list[2]+1
        #save top 10 product
        if len(self.top_count)>=10:
            if self.top_count[9][1]<count:
                self.top_count[9] = (asin,count)
                self.top_count.sort(key=lambda x:x[1],reverse=True)
        else:
            temp = (asin,count)
            self.top_count.append(temp)
            self.top_count.sort(key=lambda x:x[1],reverse=True)
        
    def getStar(self,asin):
        product = self.get_product_data(asin)
        star = product['stats_info']['avg_info']
        return star
        
    def get_product_data(self,asin):
        target_url = 'http://112.124.1.3:8004/api/commodity/'+asin+'/'
        return json.loads(urllib.urlopen(target_url).read())
    
    def getASIN(self): 
        l = []
        asin=get_ASIN()
        for page in range(0, 28):
            g = asin.write_info(self.getCategory(),page)
            l.extend(g)
        return l 
    
    #2014-05-03 00:00:00  women jeans
    #2014-03-08 00:00:00  dog food
    def getLastDay(self):
        asins = self.getASIN()
        for i in range(0,size(asins)):
            last_day = datetime.datetime(2000,1,1)
            product = self.get_product_data(asins[i])
            reviews = product['review']
            for j in range(0,size(reviews)):
                publish_time = datetime.datetime.strptime(str(reviews[j]['publishTime']).split(' ')[0],"%Y-%m-%d")
                if(publish_time>last_day):
                    last_day = publish_time
        print last_day
        #print self.get_product_data(asins[1])['productInfo'][0]['timestamp']
        
    #2014-04-23 00:00:00 women jeans
    #2014-05-13 00:00:00 dog food
    def getLocalLastDay(self):
        last_day = datetime.datetime(2000,1,1)
        lines = Review_Stuff().readFromLocal('baby_clothes_review')
        for i in range(0,len(lines)):
            reviews = lines[i]['single_review']
            for j in range(0,len(reviews)):
                publish_time = datetime.datetime.strptime(str(reviews[j]['time']).split(' ')[0],"%Y-%m-%d")
                if(publish_time>last_day):
                    last_day = publish_time
        return last_day
    
    def draw_hist(self,list):
        plt.xticks((2,12,22),(u'0',u'1-30',u'30-100'))
        rect = plt.bar(left=(2,12,22), height=self.list, width=3,align="center")
        plt.show()
        plt.show()
            
if __name__ == '__main__':
    D = draw_reviewDistibution()
    D.getLocalLastDay()
    D.getLocalRecentReviewCount()
    print D.list
    print D.top_count
    
    '''
    a = D.getASIN()
    for i in range(0,size(a)):
        D.getRecentRievewCount(a[i])
    D.draw_hist(D.list)
    '''